package com.example.Servlet;

import com.example.Service.CommentService;
import com.example.pojo.Comment;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet(name = "AddCommentServlet", value = "/AddCommentServlet")
public class AddCommentServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置响应类型和编码
        resp.setContentType("application/json;charset=utf-8");
        resp.setCharacterEncoding("UTF-8");

        BufferedReader br = req.getReader();
        StringBuffer sbuffer = new StringBuffer();
        String s = "";
        while ((s = br.readLine()) != null) {
            sbuffer.append(s);
        }

        System.out.println("接收到的评论数据:" + sbuffer.toString());

        Gson gson = new Gson();
        Map<String, Object> map = new HashMap<>();

        try {
            Comment comment = gson.fromJson(sbuffer.toString(), Comment.class);

            // 数据验证
            if (comment.getComContent() == null || comment.getComContent().trim().isEmpty()) {
                map.put("code", 400);
                map.put("msg", "评论内容不能为空");
            } else if (comment.getUserId() <= 0) {
                map.put("code", 400);
                map.put("msg", "用户ID无效");
            } else if (comment.getNewsId() <= 0) {
                map.put("code", 400);
                map.put("msg", "新闻ID无效");
            } else {
                CommentService commentService = new CommentService();
                int flag = commentService.addComment(comment);

                if (flag > 0) {
                    map.put("code", 200);
                    map.put("msg", "评论发表成功");
                    map.put("data", comment); // 返回评论数据，方便前端显示
                } else {
                    map.put("code", 500);
                    map.put("msg", "评论发表失败");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put("code", 500);
            map.put("msg", "服务器错误: " + e.getMessage());
        }

        String json = gson.toJson(map);
        System.out.println("返回响应:" + json);
        resp.getWriter().write(json);
    }

    public void destroy() {
    }
}